from datetime import date, timedelta
from rest_framework.generics import GenericAPIView
from rest_framework.mixins import ListModelMixin
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.views import APIView

from apps.goods.models import GoodsVisitCount
from apps.meiduo_admin.serializers.statistical import GoodsVisitCountSerializer
from apps.users.models import User


class UserAllCountAPIView(APIView):

    permission_classes = [IsAdminUser]

    def get(self, request):
        today = date.today()
        count = User.objects.all().count()
        return Response({
            'count': count,
            'date': today
        })


class UserDailyCountAPIView(APIView):

    permission_classes = [IsAdminUser]

    def get(self, request):
        # today = date.today() - timedelta(days=22)
        today = date.today()
        count = User.objects.filter(date_joined__gte=today).count()
        return Response({
            'count': count,
            'date': today
        })


class UserDailyActiveCountView(APIView):

    permission_classes = [IsAdminUser]

    def get(self, request):

        today = date.today()
        count = User.objects.filter(last_login__gte=today).count()
        return Response({
            'count': count,
            'date': today
        })


class UserDailyOrderCountView(APIView):

    permission_classes = [IsAdminUser]

    def get(self, request):

        today = date.today()
        count = User.objects.filter(orderinfo__create_time__gte=today)
        return Response({
            'count': count,
            'date': today
        })


class UserMonthCountView(APIView):

    permission_classes = [IsAdminUser]

    def get(self, request):

        today = date.today()
        start_date = today - timedelta(days=30)
        data  = []
        for i in range(30):
            current_date = start_date + timedelta(days=i)
            next_date = start_date + timedelta(days=i+1)
            count  = User.objects.filter(date_joined__gte=current_date, date_joined__lt=next_date).count()
            data.append({
                'count': count,
                'date': current_date
            })
        return Response(data)


class UserCategoryCountAPIView(APIView):

    permission_classes = [IsAdminUser]

    def get(self, request):

        today = date.today()
        gvcs = GoodsVisitCount.objects.filter(date=today)
        s = GoodsVisitCountSerializer(gvcs, many=True)
        return Response(s.data)